package com.lagou.edu.interceptor;

import com.lagou.edu.annotation.MySecurity;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author yuanhao
 * @version 1.0
 * @description
 * @email yuanhao@yinhai.com
 * @date 2022/4/7 11:32
 */
public class AuthorizationInterceptor implements HandlerInterceptor  {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(MySecurity.class)){
            boolean authPass = false;
            System.out.println("开始权限校验");
            MySecurity security  = method.getAnnotation(MySecurity.class);
            String[] value = security.value();
            String username = request.getParameter("username");

            int length = value.length;
            for (int i = 0; i < length; i++) {
                if (username.equalsIgnoreCase(value[i])){
                    authPass=true;
                }
            }

            if (!authPass){
                throw new RuntimeException("没有访问权限");
            }
        }
        return true;
    }

}
